<?php

// 后台首页

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;


class IndexController extends Controller
{
	// 获取字段
	const fields = "s.id,s.name,s.price,s.vip,s.status,s.is_sold_out,s.desc,s.desc2";

	public function index()
	{
		// 商品
		$skus = array();
		// 获取全部一级分类
		$category = DB::table('category')
			-> where( 'pid',0 )
			// 按权重排序
			-> orderBy( 'sort','desc' )
			-> get();
		foreach( $category as $key => $info )
		{
			// 获取商品
			$all_sku = DB::table('sku as s')
				-> select( DB::raw(self::fields),DB::raw("replace(sp.pic_url,'/image','".config('app.imgPath')."/image' ) as pic_url ") )
				-> leftJoin('sku_pic as sp','sp.sku','=','s.id')
				-> leftJoin('category as c','c.id','=','s.category_id')
				// 取封面
				-> where( 'sp.type',1)
				// sku状态 1上架 2热卖 3新品 4已下架
				-> whereIn( 's.status',array(1,2,3) )
				// 一级分类下的所有商品
				-> where( 'c.pid',$info->id )
				// 最新在先
				-> orderBy( 's.create_at','desc' )
				// 只要8条
				-> take(8)
				-> get();
			if( count($all_sku)>0 )
			{
				$skus[$key]['data'] = $all_sku;
				$skus[$key]['name'] = $info->name;
			}else
			{
				$skus[$key]['data'] = array();
				$skus[$key]['name'] = $info->name;
			}
		}
		
		return view( "index",[ 'skus'=>$skus ] );
	}
	
	
	// 后台旧首页（暂时废弃）
	public function oldIndex()
    {
		// 读取 充值相关
		$chongzhis = DB::table('log as l')
				-> select('l.*','a.name as adminName','u.name as userName')
				-> leftJoin('admin as a','a.id','=','l.admin_id')
				-> leftJoin('user as u','u.id','=','l.record_id')
				-> where('l.type',1)
				-> orderBy('l.log_at','desc')
				// 暂取30条
				-> take(30)
				-> get();
		// 读取 sku相关
		$skus = DB::table('log as l')
				-> select('l.*','a.name as adminName','s.name as skuName')
				-> leftJoin('admin as a','a.id','=','l.admin_id')
				-> leftJoin('sku as s','s.id','=','l.record_id')
				-> where('l.type',2)
				-> orderBy('l.log_at','desc')
				// 暂取30条
				-> take(30)
				-> get();
        return view( "index",[ 'chongzhis'=>$chongzhis,'skus'=>$skus ] );
    }
	
	

}
